
<template>
  <div class="dashboard-container">
    <!-- Statistics Cards -->
    <el-row :gutter="12" class="stats-row">
      <el-col :span="6" v-for="(item, index) in statsCards" :key="index">
        <div class="stats-card">
          <div class="card-content">
            <div class="card-header">
              <span class="title">{{ item.title }}</span>
              <i :class="item.icon" class="header-icon"></i>
            </div>
            <div class="main-stats">
              <div class="value-wrapper">
                <span class="value">{{ item.value }}</span>
                <span class="unit">{{ item.unit }}</span>
              </div>
            </div>
            <div class="sub-stats">
              <div class="total">{{ item.label }}: {{ item.total }}</div>
              <div class="growth-rates">
                <div class="rate-item">
                  <span class="label">同比增长率:</span>
                  <span class="value" :class="{'up': item.yoy > 0, 'down': item.yoy < 0}">
                    {{ item.yoy > 0 ? '+' : ''}}{{ item.yoy }}%
                    <i :class="item.yoy > 0 ? 'el-icon-caret-top' : 'el-icon-caret-bottom'"></i>
                  </span>
                </div>
                <div class="rate-item">
                  <span class="label">环比增长率:</span>
                  <span class="value" :class="{'up': item.mom > 0, 'down': item.mom < 0}">
                    {{ item.mom > 0 ? '+' : ''}}{{ item.mom }}%
                    <i :class="item.mom > 0 ? 'el-icon-caret-top' : 'el-icon-caret-bottom'"></i>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- Map and Equipment Status -->
    <el-row :gutter="12" class="content-row">
      <el-col :span="6">
        <el-card class="chart-card">
          <div slot="header" class="card-header">
            <span>设备状态</span>
          </div>
          <div class="pie-chart" ref="equipmentStatusChart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="map-card">
          <div id="homeMap" style="height: 100%;"></div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="info-card">
          <div slot="header" class="card-header">
            <span>充电站情况</span>
          </div>
          <div class="station-info">
            <div class="station-name">{{ stationInfo.name }}</div>
            <div class="station-address">{{ stationInfo.address }}</div>
            <div class="station-stats">
              <div>营业时间: {{stationInfo.openingStart}}～{{ stationInfo.openingEnd}}</div>
              <div>快充: {{ stationInfo.fastCharging }}</div>
              <div>慢充: {{ stationInfo.slowCharging }}</div>
              <div class="status-breakdown">
                <div>充电桩总数: {{ stationInfo.total }}</div>
                <div>空闲数: {{ stationInfo.available }} ({{ (stationInfo.available / stationInfo.total * 100).toFixed(2) }}%)</div>
                <div>使用中数: {{ stationInfo.charging }} ({{ (stationInfo.charging / stationInfo.total * 100).toFixed(2) }}%)</div>
                <div>故障数: {{ stationInfo.fault }} ({{ (stationInfo.fault / stationInfo.total * 100).toFixed(2) }}%)</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- Charts Row -->
    <el-row :gutter="12" class="charts-row">
      <el-col :span="6">
        <el-card class="trend-card">
          <div slot="header" class="card-header">
            <span>近7日充电情况（KW)</span>
          </div>
          <div class="line-chart" ref="chargeList"></div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="trend-card">
          <div slot="header" class="card-header">
            <span>近7日充电数情况（次）</span>
          </div>
          <div class="line-chart" ref="chargeCountList"></div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="trend-card">
          <div slot="header" class="card-header">
            <span>近7日充电收入情况（元）</span>
          </div>
          <div class="line-chart" ref="chargeIncomeList"></div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="trend-card">
          <div slot="header" class="card-header">
            <span>近7日充值金额情况（元）</span>
          </div>
          <div class="line-chart" ref="chargeMoneyList"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {http} from "@/api";

export default {
  name: "index",
  data() {
    return {
      map: null,
      markers: [],
      markerLayer: null,
      currentLocation: {
        // 深圳市
        lat: 22.547,
        lng: 113.945
      },
      chargingStations: [],
      loading: false,
      statsCards: [],
      charts: {
        equipmentStatusChart: null,
        chargeList: null,
        chargeCountList: null,
        chargeIncomeList: null,
        chargeMoneyList: null
      },
      stationInfo: {
        name: '',
        address: '',
        businessHours: '',
        fastCharging: '',
        slowCharging: '',
        total: 0,
        available: 0,
        charging: 0,
        fault: 0
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts()
      this.getCurrentLocation()
    })
  },
  methods: {
    // 获取当前位置
    getCurrentLocation() {
      this.initMap()
      this.fetchChargingStations()
    },

    // 获取充电站列表
    async fetchChargingStations() {
      console.log('------')
      try {
        this.loading = true
        // 假设API需要经纬度范围参数
        const response = await http.home.chargingList()
        if (response.data) {
          this.chargingStations = response.data
          this.updateMarkers(this.chargingStations[0])
        }
      } catch (error) {
        // console.error('获取充电站列表失败:', error)
        // this.$message.error('获取充电站列表失败')
      } finally {
        this.loading = false
      }
    },

    // 更新地图标记
    updateMarkers(_station = null) {
      console.log('_station',_station)
      if (!this.map) return
      if (this.markerLayer) {
        this.markerLayer.setGeometries([])
      } else {
        // 创建新的标记图层
        this.markerLayer = new TMap.MultiMarker({
          map: this.map,
          styles: {
            'normal': new TMap.MarkerStyle({
              width: 24,
              height: 30,
              anchor: { x: 15, y: 30 },
              src: require('@/assets/icon/charging-station-icon.png')
            }),
            'selected': new TMap.MarkerStyle({
              width: 34,
              height: 40,
              anchor: { x: 15, y: 30 },
              src: require('@/assets/icon/charging-station--selected-icon.png')
            })
          }
        })
      }
      // 添加充电站标记
      const markers = this.chargingStations.map((station, index) => ({
        id: index.toString(),
        styleId: _station.name === station.name ? 'selected' : 'normal',
        position: new TMap.LatLng(station.lat, station.lng),
        properties: {
          title: station.plotName,
          ...station
        }
      }))
      this.markerLayer.add(markers)
      // 添加点击事件
      this.markerLayer.on('click', (evt) => {
        const station = evt.geometry.properties
        if (station) {
          this.updateMarkers(station)
        }
      })
      this.updateStationInfo(_station)
    },

    // 更新右侧信息卡片
    updateStationInfo(station) {
      console.log('station',station)
      // 这里可以根据实际API返回的数据结构进行调整
      const stationInfo = {
        name: station.name,
        address: station.address,
        openingStart: station.openingStart,
        openingEnd: station.openingEnd,
        fastCharging: station.fastCharging || 0,
        slowCharging: station.slowCharging || 0,
        total: station.total || 0,
        available: station.available || 0,
        charging: station.charging || 0,
        fault: station.fault || 0
      }

      // 更新视图
      this.$nextTick(() => {
        // 可以通过 Vuex 或直接更新组件状态
        Object.assign(this.stationInfo, stationInfo)
      })
    },

    initMap() {
      //定义地图中心点坐标
      let center = new TMap.LatLng(this.currentLocation.lat, this.currentLocation.lng)
      //定义map变量，调用 TMap.Map() 构造函数创建地图
      this.map = new TMap.Map(document.getElementById('homeMap'), {
        center: center,//设置地图中心点坐标
        zoom: 4,   //设置地图缩放级别
      });
    },
    async initCharts() {
      http.home.cardList().then(res => {
          this.statsCards =  [
            {
              title: '本月充电量',
              value: res.data.currentDegree,
              unit: 'kwh',
              total: res.data.degreeSum,
              label: '累计充电量',
              yoy: res.data.degreeOnYear,
              mom: res.data.degreeOnMonth,
              icon: 'el-icon-lightning'
            },
            {
              title: '本月充电数',
              value: res.data.currentChargeCount,
              unit: '车次',
              total: res.data.chargeSum,
              label: '累计充电数',
              yoy: res.data.chargeCountOnYear,
              mom: res.data.chargeCountOnMonth,
              icon: 'el-icon-shopping-cart-full'
            },
            {
              title: '本月充电收入',
              value: res.data.orderAmount,
              unit: '元',
              total: res.data.orderAmountSum,
              label: '累计充电收入',
              yoy: res.data.orderAmountOnYear,
              mom: res.data.orderAmountOnMonth,
              icon: 'el-icon-money'
            },
            {
              title: '本月充值金额',
              value: res.data.userChargeAmount,
              unit: '元',
              total: res.data.userChargeAmountSum,
              label: '累计充值金额',
              yoy: res.data.userChargeAmountOnYear,
              mom: res.data.userChargeAmountOnMonth,
              icon: 'el-icon-timer'
            }
          ]
      })
      const response = await http.home.staticData()
      this.charts.equipmentStatusChart = echarts.init(this.$refs.equipmentStatusChart)
      this.charts.equipmentStatusChart.setOption({
        color: [
          '#409EFF',
          '#67C23A',
          'red'
        ],
        tooltip: {
          trigger: 'item'
        },
        legend: {
          left: 'center'
        },
        series: [{
          type: 'pie',
          radius: '50%',
          data: [
            { value: response.data.deviceStatusList.useing, name: '使用中'},
            { value: response.data.deviceStatusList.offline, name: '空闲' },
            { value: response.data.deviceStatusList.fault, name: '故障' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          label: {
            formatter: '{b}: {c} ({d}%)'
          }
        }]
      })

      const chartRefs = [
          // 'chargeList', 'chargeCountList', 'chargeIncomeList', 'chargeMoneyList'
        {
          ref: 'chargeList',
          title: '近7日充电量',
          data: response.data.chargeList.map(item => item.value),
          time: response.data.chargeList.map(item => item.time),
          unit: 'kwh'
        },
        {
          ref: 'chargeCountList',
          title: '近7日充电数',
          data: response.data.chargeCountList.map(item => item.value),
          time: response.data.chargeCountList.map(item => item.time),
          unit: '次'
        },
        {
          ref: 'chargeIncomeList',
          title: '近7日充电收入',
          data: response.data.chargeIncomeList.map(item => item.value),
          time: response.data.chargeIncomeList.map(item => item.time),
          unit: '元'
        },
        {
          ref: 'chargeMoneyList',
          title: '近7日充值金额',
          data: response.data.chargeMoneyList.map(item => item.value),
          time: response.data.chargeMoneyList.map(item => item.time),
          unit: '元'
        }
      ]

      chartRefs.forEach(refName => {
        this.charts[refName.ref] = echarts.init(this.$refs[refName.ref])
        this.charts[refName.ref].setOption({
          tooltip: {
            trigger: 'axis'
          },
          grid: {
            top: 30,
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: refName.time,
            axisLabel: {
              rotate: 45
            }
          },
          yAxis: {
            type: 'value',
            name: refName.unit,
          },
          series: [{
            data: refName.data,
            type: 'bar',
            label: {
              show: true,
              position: 'top'
            },
            barWidth: 20
          }]
        })
      })
    },
    handleResize() {
      Object.values(this.charts).forEach(chart => {
        chart && chart.resize()
      })
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    Object.values(this.charts).forEach(chart => {
      chart && chart.dispose()
    })
    // 清理地图实例
    if (this.map) {
      this.map.destroy()
    }
  },
  created() {
    window.addEventListener('resize', this.handleResize)
  }
}
</script>

<style lang="scss">
.dashboard-container {
  .content-row {
    height: 400px;
    .el-col {
      height: 100%;
      .el-card {
        height: 100%;
        display: flex;
        flex-direction: column;
        .el-card__body {
          flex-grow: 1;
          overflow: hidden;
        }
      }
    }
  }
  .stats-card {
    height: 200px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 16px 0 rgba(0,0,0,0.1);
    }

    .card-content {
      padding: 20px;

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .title {
          font-size: 14px;
          color: #909399;
        }

        .header-icon {
          font-size: 20px;
          color: #409EFF;
          opacity: 0.8;
        }
      }

      .main-stats {
        margin-bottom: 16px;

        .value-wrapper {
          display: flex;
          align-items: baseline;

          .value {
            font-size: 28px;
            font-weight: 600;
            color: #303133;
            line-height: 1;
          }

          .unit {
            margin-left: 4px;
            font-size: 14px;
            color: #909399;
          }
        }
      }

      .sub-stats {
        .total {
          font-size: 13px;
          color: #606266;
          margin-bottom: 12px;
        }

        .growth-rates {
          .rate-item {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            font-size: 13px;

            .label {
              color: #909399;
              margin-right: 12px;
            }

            .value {
              display: flex;
              align-items: center;

              &.up {
                color: #67C23A;
              }

              &.down {
                color: #F56C6C;
              }

              i {
                margin-left: 4px;
                font-size: 12px;
              }
            }
          }
        }
      }
    }
  }

  .chart-card, .map-card, .info-card, .trend-card {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);

    .card-header {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }
  }

  .pie-chart {
    height: 100%
  }
  .line-chart {
    height: 240px;
  }

  .station-info {
    .station-name {
      font-size: 16px;
      line-height: 20px;
      font-weight: 500;
      color: #303133;
      margin-bottom: 8px;
    }

    .station-address {
      font-size: 13px;
      line-height: 16px;
      color: #909399;
      margin-bottom: 16px;
    }

    .station-stats {
      font-size: 13px;
      color: #606266;

      > div {
        margin-bottom: 8px;
      }

      .status-breakdown {
        margin-top: 16px;
        padding-top: 16px;
        border-top: 1px solid #EBEEF5;
      }
    }
  }
  .map-card {
    .el-card__body {
      padding: 0; // 移除地图容器的内边距
    }
  }
}
</style>
